import axios from 'axios'
//import qs from 'qs'

const METHOD_ARR = ['GET', 'POST', 'PUT', 'DELETE'];


export function request(config) {
	config.url = 'http://127.0.0.1:8000/api/' + config.url
		
	let header = {
		'X-Requested-With': 'XMLHttpRequest'
	};
	
	let loading = config.loading ? config.loading : true;
	
	return new Promise((resolve, reject) => {
		
		if (loading) {
			uni.showLoading({title: '加载中'});
		}
		
		uni.request({
		    url: config.url, //仅为示例，并非真实接口地址。
		    data: config.data,
			method: config.method,
		    header: header,
		    success: ({data: {code,msg,data},errMsg,statusCode}) => {
				// 服务端返回的状态码
				if (code == 200) {
					uni.showToast({
						title: msg,
						duration: 3000,
						icon:'none'
					})
				}
				
				resolve(data);
		    },
			fail: (res) => {
				console.log('fail:',res);
					uni.showToast({
						title: '请求发生错误',
						duration: 5000,
						icon: 'error',
					})
				reject(res);
			},
			complete: ({data: {code,msg,data},errMsg,statusCode}) => {
				uni.hideLoading();
				
				// HTTP级别状态码
				if (statusCode === 500) {
					uni.showToast({
						title: '服务器无法响应',
						duration: 5000,
						icon: 'error',
					})
				} else if (statusCode === 404) {
					uni.showToast({
						title: 'API地址错误',
						duration: 5000,
						icon: 'error',
					})
				} else if (statusCode === 403) {
					uni.showToast({
						title: '无权访问',
						duration: 5000,
						icon: 'error',
					})
				}
				
				//console.log('comlete:',res);
			}
		});
	});
}
